<template>
  <div class="add-notes">
    <div class="main">
      <el-form :inline="true" class="form" :rules="rules" ref="formRef" :model="submitInfo">
        <el-form-item label="标题" prop="title">
          <el-input placeholder="请输入动态标题" v-model="submitInfo.title"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-select placeholder="请选择标签" @focus="getTags" @change="selectAddTag">
            <el-option v-for="item in tagsList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="tags">
          <el-tag
            style="margin-right: 5px"
            v-for="item in submitInfo.tags || []"
            :key="item.id"
            closable
            :disable-transitions="false"
            @close="handleCloseTag(item.name)"
            >{{ item.name }}</el-tag
          >
          <el-input
            v-if="inputVisable"
            v-model="inputTagValue"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
            ref="inputRef"
          ></el-input>
          <el-button v-else size="small" @click="addTag">+ 新增标签</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit(1)">提交</el-button>
          <el-button type="success" @click="submit(3)">暂存为草稿</el-button>
        </el-form-item>
        <el-form-item style="display: block">
          <el-upload
            v-model:file-list="successImgArr"
            :action="serverUploadImg"
            :headers="{ token: token }"
            list-type="picture"
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :limit="1"
          >
            <el-button type="primary">上传封面</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传封面图片</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <TextEditor v-model="submitInfo.content" />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import TextEditor from '@/components/TextEditor.vue'
import { nextTick, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { addNotesService, getNotesByIdService, updateNoteByIdService } from '@/api/Notes'
import { getTagsListService } from '@/api/Tags'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { serverStore } from '@/stores/server'
import { decryptData } from '@/utils/CryptoJSUtil'

const { serverUploadImg } = serverStore()
const route = useRoute()
const router = useRouter()
const id = route.params.id

// 提交数据
const submitInfo = ref({
  id: '',
  title: '',
  coverUrl: '',
  tags: [],
  content: '',
})
// 下拉框标签数据
const tagsList = ref([])

const formRef = ref()
// 表单验证规则
const rules = {
  title: [
    {
      required: true,
      message: '动态标题不能为空',
      trigger: 'blur',
    },
  ],
}

/**
 * 标签
 */
// 下拉标签选择
const selectAddTag = (value) => {
  console.log(submitInfo.value.tags.length)
  if (submitInfo.value.tags.length <= 2) {
    const tag = tagsList.value.find((item) => {
      if (item.id === value) {
        return item.name
      }
    })
    if (tag) {
      submitInfo.value.tags.push({ name: tag.name })
    }
  } else {
    ElMessage.error('最多只可选择3个标签')
  }
}
// 关闭标签
const handleCloseTag = (name) => {
  let index = -1
  for (let i = 0; i < submitInfo.value.tags.length; i++) {
    if (submitInfo.value.tags[i].name === name) {
      index = i
    }
  }
  if (index != -1) {
    submitInfo.value.tags.splice(index, 1)
  }
}
const inputVisable = ref(false)
const inputRef = ref()
const inputTagValue = ref('') // 输入框标签内容
const handleInputConfirm = () => {
  if (inputTagValue.value.length < 2 || inputTagValue.value.length > 5) {
    ElMessage.error('标签名称在2-5之间')
    inputTagValue.value = ''
    inputVisable.value = false
    return
  }
  if (submitInfo.value.tags.length <= 2) {
    submitInfo.value.tags.push({ name: inputTagValue.value })
    inputTagValue.value = ''
    inputVisable.value = false
  } else {
    ElMessage.error('最多只可输入3个标签')
    inputVisable.value = false
  }
}
const addTag = () => {
  inputVisable.value = true
  nextTick(() => {
    inputRef.value.input.focus()
  })
}

// 上传图片的回调数据
const successImgArr = ref([])
// 上传成功的回调函数
const handleSuccess = () => {
  ElMessage.success('上传成功')
  if (successImgArr.value[0].response && typeof successImgArr.value[0].response === 'string') {
    try {
      const decrypted = decryptData(successImgArr.value[0].response)
      const url = JSON.parse(decrypted).msg
      submitInfo.value.coverUrl = url
    } catch (err) {
      console.error('解密响应失败:', err)
    }
  }
}
const token = localStorage.getItem('token')
// 点击上传列表图片
const handlePreview = (file) => {
  console.log('列表', file)
}
// 移除出列表图片
const handleRemove = () => {
  ElMessage.success('移除图片')
  console.log('移除图片')
}
const handleError = () => {
  ElMessage.error('图片上传失败')
}
const handleExceed = () => {
  ElMessage.warning('超出上传图片上限')
}
/**
 * 获取所有标签信息
 */
const getTags = async () => {
  const { data } = await getTagsListService()
  tagsList.value = data
}
/**
 * 新增动态
 * @param status
 */
const submit = (status) => {
  formRef.value.validate((valid) => {
    if (submitInfo.value.content === '<p><br></p>') {
      ElMessage.error('文章内容信息不能为空')
      return false
    }
    if (successImgArr.value.length < 0) {
      ElMessage.error('封面照片不能为空')
      return false
    }
    if (valid) {
      // 表单验证通过
      if (id === '-1') {
        // 新增动态
        const res = addNotesService(status, submitInfo.value).then(() => {
          router.go(-1)
        })
      } else {
        // 修改动态
        submitInfo.value.id = id
        console.log('修改动态', submitInfo.value)
        updateNoteByIdService(submitInfo.value).then(() => {
          router.go(-1)
        })
      }
    }
  })
}

const getNote = async (id) => {
  if (id !== '-1') {
    const { data } = await getNotesByIdService(id)
    submitInfo.value.title = data.title
    submitInfo.value.content = data.content
    submitInfo.value.tags = data.tags
    submitInfo.value.coverUrl = data.coverUrl
    successImgArr.value.push({
      name: data.coverUrl,
      url: data.coverUrl,
    })
  }
}
onMounted(() => {
  getNote(id)
})
</script>

<style lang="scss" scoped>
* {
  border: none !important;
}
.add-notes {
  padding: 15px;
  background-color: #f3f4f5;

  .main {
    min-height: 100vh;
    border-radius: 7px;
    padding: 20px;
    background-color: #fff;

    .form {
      :deep(.el-select__wrapper) {
        width: 150px;
      }

      .tags {
        :deep(.el-input) {
          width: 60px;
          height: 24px;
        }
      }
    }
  }
}

::v-deep .w-e-scroll {
  scrollbar-width: none;
}
</style>